package com.studentmanagement.ui;

import com.studentmanagement.model.User;
import com.studentmanagement.model.Student;
import com.studentmanagement.model.Teacher;
import com.studentmanagement.service.UserService;
import com.studentmanagement.service.StudentService;
import com.studentmanagement.service.TeacherService;
import com.formdev.flatlaf.FlatClientProperties;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Date;

public class RegistrationDialog extends JDialog {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JRadioButton studentRadio;
    private JRadioButton teacherRadio;
    private ButtonGroup roleButtonGroup;
    private JButton registerButton;
    private JButton cancelButton;

    private UserService userService;
    private StudentService studentService;
    private TeacherService teacherService;

    public RegistrationDialog(Frame owner) {
        super(owner, "用户注册", true);
        userService = new UserService();
        studentService = new StudentService();
        teacherService = new TeacherService();

        initComponents();
        setupLayout();
        setupListeners();

        pack();
        setLocationRelativeTo(owner);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    }

    private void initComponents() {
        usernameField = new JTextField(20);
        passwordField = new JPasswordField(20);
        confirmPasswordField = new JPasswordField(20);
        
        // 创建角色选择的单选按钮
        studentRadio = new JRadioButton("学生");
        teacherRadio = new JRadioButton("教师");
        
        // 添加到按钮组
        roleButtonGroup = new ButtonGroup();
        roleButtonGroup.add(studentRadio);
        roleButtonGroup.add(teacherRadio);
        
        // 默认选中学生
        studentRadio.setSelected(true);
        
        registerButton = new JButton("注册");
        cancelButton = new JButton("取消");

        // 设置字体
        Font commonFont = new Font("微软雅黑", Font.PLAIN, 14);
        usernameField.setFont(commonFont);
        passwordField.setFont(commonFont);
        confirmPasswordField.setFont(commonFont);
        studentRadio.setFont(commonFont);
        teacherRadio.setFont(commonFont);
        registerButton.setFont(commonFont);
        cancelButton.setFont(commonFont);
        
        // 设置输入提示
        usernameField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "请输入用户名");
        passwordField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "请输入密码");
        confirmPasswordField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "请再次输入密码");
        passwordField.putClientProperty(FlatClientProperties.STYLE, "showRevealButton: true");
        confirmPasswordField.putClientProperty(FlatClientProperties.STYLE, "showRevealButton: true");
    }

    private void setupLayout() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        Font labelFont = new Font("微软雅黑", Font.PLAIN, 14);

        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setFont(labelFont);
        formPanel.add(usernameLabel, gbc);
        gbc.gridx = 1;
        formPanel.add(usernameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        JLabel passwordLabel = new JLabel("密 码:");
        passwordLabel.setFont(labelFont);
        formPanel.add(passwordLabel, gbc);
        gbc.gridx = 1;
        formPanel.add(passwordField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel confirmPasswordLabel = new JLabel("确认密码:");
        confirmPasswordLabel.setFont(labelFont);
        formPanel.add(confirmPasswordLabel, gbc);
        gbc.gridx = 1;
        formPanel.add(confirmPasswordField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        JLabel roleLabel = new JLabel("注册为:");
        roleLabel.setFont(labelFont);
        formPanel.add(roleLabel, gbc);
        
        // 创建角色选择面板
        JPanel rolePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 0));
        rolePanel.setOpaque(false);
        rolePanel.add(studentRadio);
        rolePanel.add(teacherRadio);
        
        // 为角色面板添加一个标题边框
        rolePanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(new Color(220, 220, 220), 1, true),
            "选择身份",
            TitledBorder.LEADING,
            TitledBorder.TOP,
            new Font("微软雅黑", Font.PLAIN, 12),
            new Color(120, 120, 120)
        ));
        
        gbc.gridx = 1;
        formPanel.add(rolePanel, gbc);

        mainPanel.add(formPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        registerButton.putClientProperty(FlatClientProperties.STYLE, "arc: 10");
        registerButton.setBackground(new Color(52, 152, 219));
        registerButton.setForeground(Color.WHITE);
        registerButton.setPreferredSize(new Dimension(100, 36));
        registerButton.setFocusPainted(false);
        
        cancelButton.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_BORDERLESS);
        cancelButton.setForeground(new Color(149, 165, 166));
        
        buttonPanel.add(registerButton);
        buttonPanel.add(cancelButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void setupListeners() {
        registerButton.addActionListener(this::performRegistration);
        cancelButton.addActionListener(e -> dispose());
    }

    private void performRegistration(ActionEvent e) {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        User.UserRole selectedRole = getSelectedRole();

        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段均为必填项。", "注册错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (!password.equals(confirmPassword)) {
            JOptionPane.showMessageDialog(this, "两次输入的密码不一致。", "注册错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 检查用户名是否已存在
        if (userService.getUserByUsername(username) != null) {
            JOptionPane.showMessageDialog(this, "用户名已存在，请选择其他用户名。", "注册错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 实际应用中密码需要加密存储
        newUser.setRole(selectedRole);

        boolean userCreated = userService.insertUser(newUser);

        if (userCreated) {
            // 获取新创建用户的ID
            User createdUser = userService.getUserByUsername(username);
            if (createdUser == null) {
                 JOptionPane.showMessageDialog(this, "用户创建成功，但获取用户信息失败！", "注册警告", JOptionPane.WARNING_MESSAGE);
                 dispose();
                 return;
            }

            // 自动创建关联的个人信息，无需用户输入
            boolean profileCreated = false;
            if (selectedRole == User.UserRole.STUDENT) {
                Student newStudent = new Student();
                newStudent.setUserId(createdUser.getId());
                newStudent.setStudentId("S" + System.currentTimeMillis() % 10000); // 生成临时学号
                newStudent.setName(username); // 使用用户名作为临时姓名
                newStudent.setBirthDate(new Date());
                profileCreated = studentService.insertStudent(newStudent);
            } else if (selectedRole == User.UserRole.TEACHER) {
                Teacher newTeacher = new Teacher();
                newTeacher.setUserId(createdUser.getId());
                newTeacher.setTeacherId("T" + System.currentTimeMillis() % 10000); // 生成临时教师工号
                newTeacher.setName(username); // 使用用户名作为临时姓名
                newTeacher.setBirthDate(new Date());
                profileCreated = teacherService.insertTeacher(newTeacher);
            }

            if (profileCreated) {
                JOptionPane.showMessageDialog(this, "用户注册成功！请使用新账户登录后完善个人信息。", "注册成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "用户账户创建成功，但档案信息未完整创建。请登录后在个人信息页面完善。", "注册部分成功", JOptionPane.WARNING_MESSAGE);
            }
            dispose(); // 关闭注册对话框
        } else {
            JOptionPane.showMessageDialog(this, "用户注册失败，请稍后再试。", "注册失败", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private User.UserRole getSelectedRole() {
        if (teacherRadio.isSelected()) {
            return User.UserRole.TEACHER;
        } else {
            return User.UserRole.STUDENT; // 默认
        }
    }
} 